import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Tab, Button, Balloon, Divider } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import {
  Header,
  Body,
  BodyContent,
  OperationBar,
  Content,
  SearchIcon,
  YunxiaoList,
} from '@alife/devops-ui';
import BranchListItem from './branchListItem';
import ListEmpty from 'atComponents/ListEmpty';
import CreateBranchModal from './createBranchModal';
import track, { enterPage, Perf } from 'utils/track';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import * as actions from '../actions/index';
import debounce from 'lodash.debounce';
import KEYCODE from 'utils/keycode';
import { ENUM } from 'utils/constants';
import BranchSkeleton from 'components/skeleton/branch';
import utils from 'utils';
import intl from '../../../../../../../locale';

const { role, isArchive } = window.FORCE.pathResource;

const tabDataSource = [
  {
    value: intl.get({
      id: 'code-assets.projectBranches.containers.root.All',
      defaultMessage: '全部',
    }),
    key: 'overview',
  },

  {
    value: intl.get({
      id: 'code-assets.projectBranches.containers.root.Mine',
      defaultMessage: '我的',
    }),

    key: 'yours',
  },

  {
    value: intl.get({
      id: 'code-assets.projectBranches.containers.root.Active',
      defaultMessage: '活跃',
    }),

    key: 'active',
  },

  {
    value: intl.get({
      id: 'code-assets.projectBranches.containers.root.Inactive',
      defaultMessage: '非活跃',
    }),

    key: 'stale',
  },
];

const { ctrlKey } = ENUM.getOSKeyMap();

class Root extends Component {
  static propTypes = {
    setTabKey: PropTypes.func,
    getBranchData: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.state = {
      search: '',
    };

    this.onSearch = debounce(this.onSearch, 500);
  }

  componentDidMount() {
    this.props.getAllData(1);
    const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
    if (isTooLarge && document.getElementById('container')) {
      document.getElementById('container').classList.add('has-too-large-tip');
    }
    enterPage('Repo-Branches', {
      sendPerf: false,
    });

    document.addEventListener('keydown', this.handleKeyCodeEvent);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.repoSize !== this.props.repoSize) {
      const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
      if (isTooLarge && document.getElementById('container')) {
        document.getElementById('container').classList.add('has-too-large-tip');
      }
    }
  }

  handleKeyCodeEvent = (e) => {
    // ctrl + / 进行搜索
    if (e[ctrlKey] && e.keyCode === KEYCODE.SPLIT) {
      document.querySelector('.search-ctrl>button').click();
      document.querySelector('.search-ctrl input').focus();
    }
  };

  componentWillUnmount() {
    this.props.resetState();
    document.removeEventListener('keydown', this.handleKeyCodeEvent);
    if (document.getElementById('container')) {
      document.getElementById('container').classList.remove('has-too-large-tip');
    }
  }

  // tab切换
  onTabChange = (tabKey) => {
    this.props.setTabKey(tabKey);
    if (tabKey === 'overview') {
      this.props.getAllData(1);
    } else {
      this.props.getBranchData(1);
    }
  };

  onSearch = (value) => {
    this.setState({
      search: value,
    });

    this.props.setTabKey('overview');
    this.props.getBranchData(1, value);
  };

  renderTab = () => {
    const { tabKey, lastMirrorSyncRecord } = this.props;

    let isMirrorSynchronizing = false;
    if (lastMirrorSyncRecord) {
      isMirrorSynchronizing = utils.isMirrorSynchronizing(lastMirrorSyncRecord.sync_status);
    }

    return (
      <div>
        <div style={{ float: 'left' }}>
          <Tab
            // className="project-branch-tab"
            style={{ padding: '20px 0' }}
            onChange={this.onTabChange}
            activeKey={tabKey}
            animation={false}
            // shape="capsule"
          >
            {tabDataSource.map((item) => (
              <Tab.Item title={item.value} key={item.key} />
            ))}
          </Tab>
        </div>
        <div style={{ float: 'right', padding: '20px 0px' }}>
          {isArchive === 'false' ? (
            <React.Fragment>
              {access(PROJECT_WRITE_ROLES, role) && !isMirrorSynchronizing ? (
                <CreateBranchModal
                  trigger={
                    <Button
                      type="primary"
                      style={{ marginLeft: 12 }}
                      onClick={() => {
                        track({
                          action: 'new_branch',
                          page: 'Repo-Branches',
                          type: '',
                          control: '',
                        });
                      }}
                    >
                      {intl.get({
                        id: 'code-assets.projectBranches.containers.root.CreateABranch',
                        defaultMessage: '新建分支',
                      })}
                    </Button>
                  }
                />
              ) : (
                <Balloon.Tooltip
                  trigger={
                    <Button type="primary" disabled style={{ marginLeft: 12 }}>
                      {intl.get({
                        id: 'code-assets.projectBranches.containers.root.CreateABranch',
                        defaultMessage: '新建分支',
                      })}
                    </Button>
                  }
                  align="l"
                  text={
                    isMirrorSynchronizing
                      ? intl.get({
                          id: 'code-assets.projectBranches.containers.root.TheRepositoryIsBeingSynchronized',
                          defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
                        })
                      : intl.get({
                          id: 'code-assets.projectBranches.containers.root.YouAreNotAuthorizedTo',
                          defaultMessage: '无权限进行新建分支操作，请联系管理员申请对应的权限',
                        })
                  }
                />
              )}
            </React.Fragment>
          ) : null}
        </div>
        <div style={{ float: 'right', padding: '20px 0px' }}>
          <SearchIcon
            direction="rtl"
            placeholder={intl.get({
              id: 'code-assets.projectBranches.containers.root.SearchForBranchName',
              defaultMessage: '搜索分支名',
            })}
            onChange={this.onSearch}
            className="search-ctrl"
            defaultValue={this.props.search}
          />
        </div>
      </div>
    );
  };

  onTitleClick = (key) => {
    this.props.setTabKey(key);
    this.props.getBranchData(1);
  };

  onPageNumberChange = (page) => {
    const { search } = this.state;
    const args = search && search.trim().length > 0 ? [page, search] : [page];
    this.props.getBranchData(...args);
  };

  onPageSizeChange = (pageSize) => {
    this.props.getBranchData(1, undefined, pageSize);
    this.props.updateData({
      pageSize,
    });
  };

  renderOverviewList = () => {
    const { isLoading, branchesData } = this.props;
    return (
      <>
        {!isLoading ? (
          <>
            {branchesData.length === 0 ? (
              this.renderEmpty()
            ) : (
              <YunxiaoList
                dataSource={branchesData}
                renderItem={(br) => <BranchListItem branchDataSource={br} {...this.props} />}
              />
            )}
          </>
        ) : (
          this.renderSkeleton()
        )}
      </>
    );
  };

  renderSkeleton = () => {
    return <BranchSkeleton delay={500} />;
  };

  renderEmpty = () => {
    const { search } = this.state;
    return (
      <ListEmpty
        type="project"
        content={
          search
            ? null
            : intl.get({
                id: 'code-assets.projectBranches.containers.root.NoBranch',
                defaultMessage: '暂无分支',
              })
        }
        description={search ? '抱歉，未找到匹配结果' : null}
        imgType={search ? 'search' : 'none'}
        fullPage
      />
    );
  };

  renderOtherList = () => {
    const { branchesData, isLoading } = this.props;
    return (
      <>
        {!isLoading ? (
          <>
            {branchesData.length === 0 ? (
              this.renderEmpty()
            ) : (
              <>
                <YunxiaoList
                  dataSource={branchesData}
                  renderItem={(br) => <BranchListItem branchDataSource={br} {...this.props} />}
                />
              </>
            )}
          </>
        ) : (
          this.renderSkeleton()
        )}
      </>
    );
  };

  render() {
    const { isLoading, tabKey, lastMirrorSyncRecord, currentPage, total } = this.props;

    let isMirrorSynchronizing = false;
    if (lastMirrorSyncRecord) {
      isMirrorSynchronizing = utils.isMirrorSynchronizing(lastMirrorSyncRecord.sync_status);
    }

    return (
      <>
        <Header
          title={intl.get({
            id: 'code-assets.projectBranches.containers.root.Branch',
            defaultMessage: '分支',
          })}
          operation={
            isArchive === 'false' ? (
              <React.Fragment>
                <SearchIcon
                  direction="rtl"
                  placeholder={intl.get({
                    id: 'code-assets.projectBranches.containers.root.SearchForBranchName',
                    defaultMessage: '搜索分支名',
                  })}
                  onChange={this.onSearch}
                  className="search-ctrl"
                  defaultValue={this.props.search}
                />
                <Divider direction="ver" />
                {access(PROJECT_WRITE_ROLES, role) && !isMirrorSynchronizing ? (
                  <CreateBranchModal
                    trigger={
                      <Button
                        type="primary"
                        onClick={() => {
                          track({
                            action: 'new_branch',
                            page: 'Repo-Branches',
                            type: '',
                            control: '',
                          });
                        }}
                      >
                        {intl.get({
                          id: 'code-assets.projectBranches.containers.root.CreateABranch',
                          defaultMessage: '新建分支',
                        })}
                      </Button>
                    }
                  />
                ) : (
                  <Balloon.Tooltip
                    trigger={
                      <Button type="primary" disabled style={{ marginLeft: 12 }}>
                        {intl.get({
                          id: 'code-assets.projectBranches.containers.root.CreateABranch',
                          defaultMessage: '新建分支',
                        })}
                      </Button>
                    }
                    align="l"
                    text={
                      isMirrorSynchronizing
                        ? intl.get({
                            id: 'code-assets.projectBranches.containers.root.TheRepositoryIsBeingSynchronized',
                            defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
                          })
                        : intl.get({
                            id: 'code-assets.projectBranches.containers.root.YouAreNotAuthorizedTo',
                            defaultMessage: '无权限进行新建分支操作，请联系管理员申请对应的权限',
                          })
                    }
                  />
                )}
              </React.Fragment>
            ) : null
          }
        />

        <Body>
          <BodyContent>
            <OperationBar>
              <Tab onChange={this.onTabChange} activeKey={tabKey} animation={false}>
                {tabDataSource.map((item) => (
                  <Tab.Item title={item.value} key={item.key} />
                ))}
              </Tab>
            </OperationBar>

            <Content>
              {!isLoading ? (
                <>
                  {tabKey === 'overview' ? this.renderOverviewList() : this.renderOtherList()}
                  <Perf page={'Repo-Branches'} />
                </>
              ) : (
                this.renderSkeleton()
              )}
            </Content>
            <Pagination
              onChange={this.onPageNumberChange}
              onPageSizeChange={this.onPageSizeChange}
              pageSize={this.props.pageSize}
              current={currentPage}
              total={total}
            />
          </BodyContent>
        </Body>
      </>
      // <div className="project-content branch-content">
      //   {this.renderTab()}
      //   {!isLoading ? (
      //     <div>
      //       {tabKey === 'overview' ? this.renderOverviewList() : this.renderOtherList()}
      //       <Perf page={'Repo-Branches'} />
      //     </div>
      //   ) : (
      //     this.renderSkeleton()
      //   )}
      // </div>
    );
  }
}

export default connect(
  (state) => ({
    ...state.project.projectBranches,
    projectInfo: state.project.root.projectInfo,
    pageInfo: state.root.pageInfo,
    lastMirrorSyncRecord: state.project.root.lastMirrorSyncRecord,
  }),

  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
